 <template>
  <d2-container>
    <!-- 数据分配 导入 -->
    <el-dialog
      title="分配数据 (先搜索再分配！)"
      :visible.sync="dialogDataDistributeVisible"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-row style="width:100%">
        <!-- <el-tree :props="defaultProps" :load="loadNode" lazy></el-tree> -->
        <el-tree
          ref="tree"
          :props="defaultProps"
          :data="treeData"
          node-key="id"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
          show-checkbox
        ></el-tree>
      </el-row>
      <el-row>
        <el-divider content-position="left">分配条数(搜到1万条数据只想分100条，就在下面写100就行)</el-divider>
        <el-input v-model="recordNumber"></el-input>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="allocate()" icon="el-icon-check" size="mini">确认分配</el-button>
      </div>
    </el-dialog>

    <!-- excel 导入 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogImportExcelVisible"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      v-loading="isLoading"
      element-loading-text="系统正在处理中..."
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <el-row>
        <div class="d2-mb">
          <el-button @click="download">
            <d2-icon name="download" />下载导入模板
          </el-button>
        </div>

        <div class="d2-mb">
          <el-upload
            ref="upload"
            :action="VUE_APP_UPLOAD_FILE_URL"
            :headers="{Authorization: _token}"
            :limit="1"
            :data="uploadParam"
            :auto-upload="false"
            :on-success="handleSuccess"
            :on-error="handleError"
          >
            <el-button size="medium" type="success">选择导入文件</el-button>
          </el-upload>
        </div>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-select v-model="insurer" placeholder="请选择" filterable clearable>
            <el-option
              v-for="item in options6"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-input type="textarea" :rows="2" placeholder="请输入批次操作备注信息" v-model="batchRemarks"></el-input>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importXls()" icon="el-icon-check" size="mini">确定导入</el-button>
      </div>
    </el-dialog>

    <!-- header 查询条件 -->
    <template slot="header">
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1" title="更多操作">
          <el-form :inline="true" :model="listQuery" size="mini" style="margin-bottom: -18px;">
            <el-row>
              <el-col :span="24">
                <el-form-item style="float: left">
                  <el-button @click="handleCreate" type="primary" icon="el-icon-plus">新 增</el-button>
                  <el-button @click="handleBatchDelete" type="primary" icon="el-icon-delete">批量删除</el-button>

                  <el-button
                    @click="showImportExcelDlg"
                    type="primary"
                    icon="fa fa-upload"
                  >&nbsp;导入 Excel</el-button>
                  <el-button
                    @click="exportExcel"
                    type="primary"
                    icon="fa fa-download"
                  >&nbsp;导出 Excel</el-button>&nbsp;
                  <el-select v-model="value" placeholder="请选择分配对象" filterable clearable>
                    <el-option-group
                      v-for="group in options"
                      :key="group.label"
                      :label="group.label"
                    >
                      <el-option
                        v-for="item in group.options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-option-group>
                  </el-select>&nbsp;
                  <el-button
                    v-if="coustomer_distribution"
                    @click="handleAssign"
                    type="primary"
                    icon="fa fa-paper-plane-o"
                  >&nbsp;手工分配数据</el-button>
                  <el-button
                    v-if="coustomer_distribution"
                    @click="handleAssign2"
                    type="primary"
                    icon="fa fa-paper-plane-o"
                  >批量分配数据</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="数据分类" prop="username">
              <el-select v-model="listQuery.client_type" placeholder="请选择" filterable clearable>
                <el-option
                  v-for="item in options3"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数据分组" prop="username">
              <el-select v-model="listQuery.success" placeholder="请选择" filterable clearable>
                <el-option
                  v-for="item in options2"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="业务员" prop="username">
              <el-select v-model="listQuery.yewyId" placeholder="请选择" filterable clearable>
                <el-option
                  v-for="item in yewyList"
                  :key="item.userId"
                  :label="item.realName"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分配状态" v-if="coustomer_distribution">
              <el-select v-model="listQuery.allocation" placeholder="请选择" filterable clearable>
                <el-option
                  v-for="item in options5"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="车牌" prop="username">
              <el-input
                @keyup.enter.native="handleFilter"
                style="width: 200px;"
                placeholder
                v-model="listQuery.car_no"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="车主" prop="username">
              <el-input
                @keyup.enter.native="handleFilter"
                style="width: 200px;"
                placeholder
                v-model="listQuery.car_owner"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="车型" prop="username">
              <el-input
                @keyup.enter.native="handleFilter"
                style="width: 200px;"
                placeholder
                v-model="listQuery.vehicle_type"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="商业险到期日期" prop="username">
              <el-date-picker
                v-model="listQuery.viEndDate"
                type="daterange"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="交强险到期日期" prop="username">
              <el-date-picker
                v-model="listQuery.clivtaEndDate"
                type="daterange"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="初登日期" prop="username">
              <el-date-picker
                v-model="listQuery.firstRegistrationDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="default" @click="handleFilter" icon="el-icon-search">搜 索</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </template>

    <!-- table表格 -->
    <el-table
      ref="multipleTable"
      :key="tableKey"
      :data="list"
      @selection-change="handleSelectionChange"
      highlight-current-row
      stripe
      style="width: 100%;"
      sortable="custom"
      @sort-change="sortChange"
      height="100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <!-- <el-table-column type="index" align="center" label="序号" width="60"></el-table-column> -->
      <el-table-column align="center" label="保险公司" width="150">
        <template slot-scope="scope">
          <span>{{scope.row.insurerName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="业务员" width="100" v-if="coustomer_distribution">
        <template slot-scope="scope">
          <span>{{scope.row.userName == null ? "未分配" : scope.row.userName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="数据分组" width="150">
        <template slot-scope="scope">
          <span>{{scope.row.success}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="数据分类" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.clientTypeName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="车牌" width="150">
        <template slot-scope="scope">
          <span>{{scope.row.carNo}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="车主" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.carOwner}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="车型" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.vehicleType}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="商业险到期日期"
        show-overflow-tooltip
        width="150"
        sortable
        prop="clivtaEndDate"
      >
        <template slot-scope="scope">
          <span>{{scope.row.viEndDate | parseTime('{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="交强险到期日期"
        show-overflow-tooltip
        width="150"
        sortable
        prop="clivtaEndDate"
      >
        <template slot-scope="scope">
          <span>{{scope.row.clivtaEndDate | parseTime('{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>
       <el-table-column
        align="center"
        label="初登日期"
        show-overflow-tooltip
        width="150"
        sortable
        prop="clivtaEndDate"
      >
        <template slot-scope="scope">
          <span>{{scope.row.firstRegistrationDate | parseTime('{y}-{m}-{d}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.note}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="更新时间" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.modificationDate | parseTime('{y}-{m}-{d} {h}:{m}:{s}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.createDate | parseTime('{y}-{m}-{d} {h}:{m}:{s}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="最后一次通话时间" show-overflow-tooltip width="200">
        <template slot-scope="scope">
          <span>{{scope.row.lastCallTime | parseTime('{y}-{m}-{d} {h}:{m}:{s}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            @click="handleDetial(scope.row)"
            icon="fa fa-bar-chart"
          ></el-button>
          <el-button
            v-if="sys_user_upd"
            size="mini"
            type="primary"
            @click="handleUpdate(scope.row)"
            icon="el-icon-edit"
          ></el-button>
          <el-button
            v-if="sys_user_del"
            size="mini"
            type="danger"
            @click="deletes(scope.row)"
            icon="el-icon-delete"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- footer 分页条 -->
    <template slot="footer">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.page"
        :page-sizes="[50]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: -10px;"
      ></el-pagination>
    </template>
    <!-- 新增客户信息弹框 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="80px" size="mini">
        <el-row style="width:100%">
          <el-col :span="12">
            <el-form-item label="分类" placeholder prop="carNo">
              <el-select v-model="value3" placeholder="请选择">
                <el-option
                  v-for="item in options3"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车牌" placeholder prop="carNo">
              <el-input v-model="form.carNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车架" placeholder prop="vehicleNo">
              <el-input v-model="form.vehicleNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发动机" placeholder prop="engineNumber">
              <el-input v-model="form.engineNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车主" placeholder prop="carOwner">
              <el-input v-model="form.carOwner"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="被保险人" placeholder prop="carOwner">
              <el-input v-model="form.insured"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" placeholder prop="carOwner">
              <el-input v-model="form.insuredIdCard"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" placeholder prop="mobilePhone">
              <el-input v-model="form.mobilePhone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话2" placeholder prop="standbyMobile">
              <el-input v-model="form.standbyMobile"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="初登日期" placeholder prop="firstRegistrationDate">
              <el-date-picker
                v-model="form.firstRegistrationDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交强日期" placeholder prop="firstRegistrationDate">
              <el-date-picker
                v-model="form.clivtaEndDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商业日期" placeholder prop="firstRegistrationDate">
              <el-date-picker
                v-model="form.viEndDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')" icon="el-icon-close" size="mini">取 消</el-button>
        <el-button
          v-if="dialogStatus=='create'"
          type="primary"
          @click="create('form')"
          icon="el-icon-check"
          size="mini"
        >确 定</el-button>
        <el-button
          v-else
          type="primary"
          @click="update('form')"
          icon="el-icon-check"
          size="mini"
        >修 改</el-button>
      </div>
    </el-dialog>
  </d2-container>
</template>

<script>
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  getTreeData,
  importData,
  getAassignList,
  assignData,
  assignData4Manual,
  batchDelObj,
  insertBookingByClientId,
  batchMoveSellData
} from "@/api/customer";

import * as callcenter from "@/api/callcenter";
import * as newcomer from "@/api/newcomer";
import * as user from "@/api/user";

import { deptRoleList, fetchDeptTree } from "@/api/role";
import { mapGetters, mapState } from "vuex";
import ElRadioGroup from "element-ui/packages/radio/src/radio-group";
import ElOption from "element-ui/packages/select/src/option";
// Import component
import Loading from "vue-loading-overlay";
// Import stylesheet
import "vue-loading-overlay/dist/vue-loading.css";

import util from "@/libs/util";

export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + "";
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      );
    }
  }
  return fmt;
}

function padLeftZero(str) {
  return ("00" + str).substr(str.length);
}

export default {
  name: "数据管理",
  components: {
    ElOption,
    ElRadioGroup,
    Loading
  },
  data() {
    return {
      insurer: null,
      recordNumber: -1,
      selectedTreeNode: {},
      treeData: null,
      yewyList: [],
      defaultProps: {
        children: "children",
        label: "deptName"
      },
      dialogDataDistributeVisible: false,
      activeNames: ["1"],
      myHeaders: {},
      uploadParam: {},
      batchRemarks: null,
      isStrict: true,
      reserveDateTime: null,
      // 分配数据
      options: [],
      value: "",
      // 移动数据
      options2: [],
      value2: "",
      // 分类
      options3: [],
      value3: "",
      // 已分配未分配
      options5: [
        {
          label: "已分配",
          value: 1
        },
        {
          label: "未分配",
          value: 0
        }
      ],

      // 续保日期
      options4: [
        {
          value: "-1",
          label: "所有"
        },
        {
          value: "30",
          label: "30天"
        },
        {
          value: "60",
          label: "60天"
        },
        {
          value: "90",
          label: "90天"
        }
      ],
      value4: "",
      // 保险公司列表
      options6: [],
      props: {
        label: "name",
        children: "666"
      },
      count: 1,
      filename: __filename,
      table: {
        columns: [],
        data: [],
        size: "mini",
        stripe: true,
        border: true
      },
      callList: null,
      isLoading: false,
      treeDeptData: [],
      checkedKeys: [],
      list: null,
      total: null,
      listQuery: {
        page: 1,
        limit: 50,
        car_owner: null,
        car_no: null,
        client_type: null,
        insEndDate: null,
        success: null
      },
      form: {
        carNo: undefined,
        vehicleNo: undefined,
        engineNumber: undefined,
        carOwner: undefined,
        mobilePhone: undefined,
        vehicleType: undefined,
        firstRegistrationDate: undefined
      },
      rules: {},
      statusOptions: ["0", "1"],
      rolesOptions: [],
      dialogFormVisible: false,
      dialogDetailVisible: false,
      dialogDeptVisible: false,
      dialogImportExcelVisible: false,
      dialogAssignVisible: false,
      userAdd: false,
      userUpd: false,
      userDel: false,
      dialogStatus: "",
      textMap: {
        update: "编辑客户信息",
        create: "新增客户信息",
        import: "导入业务数据",
        assign: "分配业务数据"
      },
      isDisabled: {
        0: false,
        1: true
      },
      tableKey: 0,
      multipleSelection: []
    };
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: "有效",
        1: "无效",
        9: "锁定"
      };
      return statusMap[status];
    }
  },
  computed: {
    // ...mapGetters(['permissions']),
    ...mapState("d2admin/user", ["info"]),
    _token: {
      get: function() {
        return "Bearer " + util.cookies.get("token");
      }
    },
    VUE_APP_UPLOAD_FILE_URL: {
      get: function() {
        return `${process.env.VUE_APP_UPLOAD_FILE_URL}`;
      }
    }
  },
  created() {
    this.sys_user_add = this.hasFunctions(["sys_user_add"]);
    this.sys_user_upd = this.hasFunctions(["sys_user_upd"]);
    this.sys_user_del = this.hasFunctions(["sys_user_del"]);

    this.customer_import = this.hasFunctions(["customer_import"]);
    this.customer_export = this.hasFunctions(["customer_export"]);
    this.coustomer_delete = this.hasFunctions(["coustomer_delete"]);
    this.coustomer_batch_delete = this.hasFunctions(["coustomer_batch_delete"]);
    this.coustomer_distribution = this.hasFunctions(["coustomer_distribution"]);

    getAassignList().then(resp => {
      console.log(resp);
      this.options = resp.result;
    });

    getTreeData(10).then(resp => {
      console.log(resp);
      this.treeData = resp.result;
    });

    newcomer.queryDictListByType("clientGrouping").then(resp => {
      console.log(resp);
      this.options2 = resp.records;
    });

    newcomer.queryDictListByType("clientType").then(resp => {
      console.log(resp);
      this.options3 = resp.records;
    });

    newcomer.queryDictListByType("insurer").then(resp => {
      console.log(resp);
      this.options6 = resp.records;
    });

    // 业务员
    user.fetchList(this.listQuery).then(resp => {
      console.log(resp);
      this.yewyList = resp.records;
    });

    // null 是所有客户
    this.listQuery.success = null;
    this.getList();
  },
  methods: {
    // 新版本分配数据
    allocate() {
      let checkedNodes = this.$refs.tree.getCheckedNodes();

      let yewy_ids = [];
      checkedNodes.forEach(element => {
        console.log(element);
        if (element.nodeType == "user") yewy_ids.push(element.id);
      });

      this.$confirm("确认分配么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 按查询条件分配数据
        this.listQuery.yewy_ids = yewy_ids;
        // this.listQuery.allocation = 0;
        this.listQuery.record = this.recordNumber;

        assignData(this.listQuery).then(resp => {
          console.log(resp);
          if (resp.status == "SUCCEED") {
            let result = "";
            resp.result.forEach(element => {
              result += element.userName + ", " + element.total + ";";
            });
            this.$message({
              type: "success",
              message: "分配结果, " + result
            });

            this.listQuery.yewy_ids = null;
            this.getList();
          }
        });
      });
    },

    loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([{ deptName: "组织机构", parentId: 10 }]);
      }

      // if (node.level > 1)
      //   return resolve([]);

      // const data = [
      //   {
      //     name: "666",
      //     leaf: true
      //   }
      // ];

      getTreeData(node.data.parentId).then(resp => {
        console.log(resp);

        resolve(resp.result);
      });
    },

    sortChange(_column) {
      this.listQuery.orderByField = _column.prop;
      if (_column.order == "descending") this.listQuery.isAsc = false;
      else this.listQuery.isAsc = true;

      this.getList();
    },

    handleSuccess(response, file, fileList) {
      this.isLoading = false;
      console.log("文件上传 success");

      if (response.status == "SUCCEED") {
        this.$message({
          type: "success",
          message: response.extMessage
        });

        this.batchRemarks =
          response.extMessage + "\r\n" + response.result.repeat;
      } else {
        this.$message({
          type: "error",
          message: response.errorMessage
        });
      }
    },

    handleError(err, file, fileList) {
      this.isLoading = false;
      console.log("文件上传 error");
      this.$message({
        type: "error",
        message: "导入文件失败"
      });
    },

    reserve() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: "error",
          message: "请选择一条预约数据"
        });
        return;
      }

      if (this.multipleSelection.length > 1) {
        this.$message({
          type: "error",
          message: "预约数据，只能单选！"
        });
        return;
      }

      let newDt = formatDate(this.reserveDateTime, "yyyy-MM-dd hh:mm:ss");
      insertBookingByClientId({
        clientId: this.multipleSelection[0].id,
        bookingTime: newDt
      }).then(resp => {
        console.log(resp);
        if (resp.status == "SUCCEED") {
          this.$message({
            type: "success",
            message: "预约成功"
          });
        } else {
          this.$message({
            type: "error",
            message: "预约失败"
          });
        }
      });
    },

    handleMove() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: "error",
          message: "请选择要操作的数据"
        });
        return;
      }

      let ids = [];
      this.multipleSelection.forEach(element => {
        ids.push(element.id);
      });

      // clientGrouping1
      // {ids: [], status: 'clientGrouping1'}
      batchMoveSellData({ ids: ids, status: this.value2 }).then(resp => {
        console.log(resp);
        if (resp.status == "SUCCEED") {
          this.$message({
            type: "success",
            message: "操作成功"
          });

          this.getList();
        } else {
          this.$message({
            type: "error",
            message: "操作失败"
          });
        }
      });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleBatchDelete() {
      this.$confirm("确认删除么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let ids = [];
        this.multipleSelection.forEach(element => {
          ids.push(element.id);
        });

        batchDelObj(ids).then(resp => {
          console.log(resp);
          this.$message({
            type: "success",
            message: "删除成功"
          });

          this.getList();
        });
      });
    },

    importXls() {
      // {"isValidate":"","remark":"","list":[]}
      // let input = {
      //   list: this.table.data,
      //   isValidate: this.isStrict == true ? 1 : 0,
      //   remark: this.batchRemarks
      // };

      // importData(input).then(resp => {
      //   console.log(resp);
      //   this.isLoading = false;

      //   if (resp.status == "SUCCEED") {
      //     this.$confirm(resp.result, "提示", {
      //       confirmButtonText: "确定",
      //       showCancelButton: false,
      //       type: "success"
      //     });
      //   } else
      //     this.$message({
      //       type: "error",
      //       message: resp.errorMessage
      //     });
      // });

      if (this.insurer == undefined) {
        this.$message({
          type: "error",
          message: "请选择保险公司"
        });
        return;
      }

      if (this.$refs.upload.uploadFiles.length == 0) {
        this.$message({
          type: "error",
          message: "先选择文件后，才能点击确认导入！"
        });
        return;
      }

      if (this.batchRemarks == null || this.batchRemarks.length < 5) {
        this.$message({
          type: "error",
          message: "备注信息最少填写5个字！"
        });
        return;
      }

      this.uploadParam.isValidate = 0;
      this.uploadParam.remark = this.batchRemarks;
      this.uploadParam.insurer = this.insurer;

      this.$refs.upload.submit();
      this.isLoading = true;
    },

    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
    },

    handleNodeClick(data) {
      console.log(data);
      this.selectedTreeNode = data;
    },

    handleUpload(file) {
      this.$import.xlsx(file).then(({ header, results }) => {
        this.table.columns = header.map(e => {
          return {
            label: e,
            prop: e
          };
        });
        this.table.data = results;
      });
      return false;
    },

    download() {
      window.location.href =
        "http://media.avicyt.com/%E8%BD%A6%E8%BE%86%E4%BF%A1%E6%81%AF%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF1.0.xls";
    },

    showImportExcelDlg() {
      this.dialogStatus = "import";
      this.dialogImportExcelVisible = true;
      this.table.columns = [];
      this.table.data = [];
    },

    exportExcel() {
      window.location.href =
        "http://media.avicyt.com/%E8%BD%A6%E8%BE%86%E4%BF%A1%E6%81%AF%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xls";
    },

    getList() {
      this.isLoading = true;
      this.listQuery.isAsc = false;
      fetchList(this.listQuery).then(response => {
        this.list = response.records;
        this.total = response.total;
        this.isLoading = false;
      });
    },
    getNodeData(data) {
      this.dialogDeptVisible = false;
      this.form.deptId = data.id;
      this.form.deptName = data.name;
      deptRoleList(data.id).then(response => {
        this.rolesOptions = response;
      });
    },
    handleDept() {
      fetchDeptTree().then(response => {
        this.treeDeptData = response;
        this.dialogDeptVisible = true;
      });
    },
    handleFilter() {
      let tmp = this.listQuery.viEndDate;
      if (tmp != undefined) {
        this.listQuery.viEndDate = tmp[0];
        this.listQuery.viEndDateEnd = tmp[1];
      }

      tmp = this.listQuery.clivtaEndDate;
      if (tmp != undefined) {
        this.listQuery.clivtaEndDate = tmp[0];
        this.listQuery.clivtaEndDateEnd = tmp[1];
      }

      this.listQuery.page = 1;

      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      // deptRoleList(this.info.deptId).then(response => {
      //   this.rolesOptions = response.data
      // })
    },
    // 老版本分配数据
    handleAssign() {
      if (this.value == "") {
        this.$message({
          type: "error",
          message: "请选择分配对象"
        });
        return;
      }

      this.$confirm("确认分配么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let clientIds = [];
        this.multipleSelection.forEach(element => {
          clientIds.push(element.id);
        });

        assignData4Manual({userId: this.value, clientIds: clientIds}).then(resp => {
          console.log(resp);
          if(resp.status == "SUCCEED") {
            this.$message({
              type: "success",
              message: "分配成功, 分配给: " + resp.result.userName + ", " + resp.result.total + " 条数据",
              duration: 3000
            });
            this.getList();
          }
        });
      });
    },

    handleAssign2() {
      this.dialogDataDistributeVisible = true;
    },

    handleUpdate(row) {
      this.form = row;
      this.dialogFormVisible = true;
      this.dialogStatus = "update";
    },
    create(formName) {
      const set = this.$refs;
      this.form.role = this.role;
      set[formName].validate(valid => {
        if (valid) {
          this.form.userId = this.info.id;

          addObj(this.form).then(resp => {
            debugger;
            if (
              resp.errorMessage != undefined &&
              resp.errorMessage.indexOf("重复") > 0
            ) {
              this.$notify({
                title: "提示",
                message:
                  "车牌号重复，如果自己账号下搜不到。可能分配了给别人，联系主管重新分配数据",
                type: "error"
              });
              return;
            }

            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "提示",
              message: "创建成功",
              type: "success"
            });
          });
        } else {
          return false;
        }
      });
    },
    cancel(formName) {
      this.dialogFormVisible = false;
      this.dialogAssignVisible = false;
      this.$refs[formName].resetFields();
    },

    update(formName) {
      const set = this.$refs;
      // this.form.role = this.role
      console.log(this.form);
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false;
          this.form.password = undefined;

          this.form.clientType = this.value3;
          this.form.mobilePhone = null;
          this.form.standbyMobile = null;

          putObj(this.form).then(() => {
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    },

    deletes(row) {
      this.$confirm("确认删除么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delObj(row.id)
          .then(() => {
            this.getList();
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
          })
          .cache(() => {
            this.$notify({
              title: "失败",
              message: "删除失败",
              type: "error",
              duration: 2000
            });
          });
      });
    },

    handleDetial(row) {
      if (row.firstRegistrationDate != null)
        row.firstRegistrationDate = row.firstRegistrationDate.split(" ")[0];

      this.$router.push({
        path: "/customer/detail",
        query: { id: row.id, clientName: row.carOwner, obj: row }
      });
    },

    resetTemp() {
      this.form = {
        id: undefined,
        username: "",
        password: "",
        roleList: [],
        delFlag: "",
        deptId: "",
        phone: ""
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.d2-mb {
  float: left;
  margin-right: 20px;
}
.d2-mb .el-button i {
  margin-right: 4px;
}

.el-row {
  margin-bottom: 10px;
  &:last-child {
    margin-bottom: 0;
  }
}
</style>
